<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2017/3/15
  Time: 20:45
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Ajax实现Selet</title>
<script type="text/javascript" src="../js/ajax.js"></script>
</head>
<body>
<select name="provice" id="provinceID" style="width: 111px;">
    <option >选择省份</option>
    <option >湖南</option>
    <option >广东</option>
</select>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<select name="provice" id="cityID" style="width: 111px;">
    <option >选择城市</option>
</select>

<%--接下来监听 select 的选择事件 --%>
<script type="text/javascript">
    document.getElementById("provinceID").onchange = function () {
        // 清空城市列表
        var cityElement = document.getElementById("cityID");
        cityElement.options.length=1;
        //获取省份信息
        var optionElement = this[this.selectedIndex];
        var proviceName = optionElement.innerHTML;

        if("选择省份"!=proviceName){
            var ajax = createAJAX();
            var url = "${pageContext.request.contextPath}/select"
            ajax.open("POST",url);
            ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");
            var params = "province="+proviceName;
            ajax.send(params);
            ajax.onreadystatechange = function () {
                if(ajax.readyState==4){
                    if(ajax.status==200){
//                      这里获取他的XML 类型；response 必须指定该类型
                        var xmlDoc = ajax.responseXML;
//                        解析XML文档
                        var cityElementArray = xmlDoc.getElementsByTagName("city");
                        var size = cityElementArray.length;
                        for(var i=0;i<size;i++){
                            var city = cityElementArray[i].firstChild.nodeValue;
                            var option = document.createElement("option");
                            option.innerHTML=city;
                            cityElement.appendChild(option);
                        }

                    }
                }
            }



        }
    }
</script>

</body>
</html>
